#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main()
{
  pid_t pid;
  int fd, count;
  char buf[1024];
  int fds[2];
  if (pipe(fds) < 0)
  {
    perror("管道创建失败");
    return -1;
  }

  while (1)
  {
    pid = fork();
    if (pid == 0)
    {
      char buf2[1024] = {0};

      int count2 = read(fds[0], buf2, sizeof(buf2));
      if (count2 <= 0)
      {
        perror("子进程读取管道失败");
        exit(-1);
      }

      printf("子进程读取到数据：%s,count = %d\n", buf2, count2);

      if (count2 == 3 && strncmp(buf2, "end", 3) == 0)
      {
        printf("子进程退出\n");
        close(fds[0]);
        exit(0); // 退出
      }

      // 分割字符串,解析命令
      char *argv[1024];
      int i = 0;
      argv[i++] = strtok(buf2, " ");
      while (argv[i - 1] != NULL)
      {
        argv[i++] = strtok(NULL, " ");
      }

      close(fds[0]); // 关闭管道
      execvp(argv[0], argv);
      perror("子进程执行失败");
      exit(-1);
    }
    else if (pid > 0)
    {
      // 父进程执行

      count = read(0, buf, sizeof(buf));
      // 清除换行符
      buf[count - 1] = '\0';

      write(fds[1], buf, count - 1);
      // 判断buf里面是不是end
      if ((count - 1) == 3 && strncmp(buf, "end", 3) == 0)
      {
        wait(NULL);
        printf("父进程退出\n");
        close(fds[1]);
        exit(0); // 退出
      }

      wait(NULL); // 等待子进程退出
      printf("父进程执行完一次\n");
    }
    else
    {
      perror("子进程创建失败");
      exit(-1);
    }
  }
  return 0;
}
